package com.bluexmicro.android.upgradebox.screen.file

import android.content.Context
import android.os.Environment
import java.io.File
import java.io.FileFilter
import java.io.InputStream

object FileUtils {

    val binFilter = FileFilter {
        val extensions = mutableListOf("bin")
        if (it.isHidden || it.startsWith(".")) {
            return@FileFilter false
        }
        if (it.isDirectory) {
            return@FileFilter true
        }
        return@FileFilter extensions.contains(it.extension.lowercase())
    }

}

fun File.displayName(): String {
    return if (this == Environment.getExternalStorageDirectory()) {
        "External Storage"
    } else {
        this.name
    }
}

/**
 * 计算文件大小
 */
fun File.contentSize(context: Context): String {
    val isDefaultFirmware = this.path.contains("firmware/default")
    if (!this.isFile) {
        return "0B"
    }
    val byteCount = if (isDefaultFirmware) {
        val `in`: InputStream = context.resources.assets.open(this.path)
        //获取bai文du件的zhi字dao节内数容
        try {
            `in`.available()
        } catch (e: Exception) {
            0
        }.toLong()
    } else {
        this.length()
    }
    val KB = 1024
    val MB = 1024 * 1024
    val GB = 1024 * 1024 * 1024
    return when (byteCount) {
        in 0 until KB -> {
            "$byteCount" + "B"
        }
        in KB until MB -> {
            "${byteCount / KB}KB"
        }
        in MB until GB -> {
            "${byteCount / MB}MB"
        }
        else -> {
            "${byteCount / GB}GB"
        }
    }
}

fun Int.toFileSize(): String {
    val KB = 1024
    val MB = 1024 * 1024
    val GB = 1024 * 1024 * 1024
    return when (this) {
        in 0 until KB -> {
            "$this" + "B"
        }
        in KB until MB -> {
            "${this / KB}KB"
        }
        in MB until GB -> {
            "${this / MB}MB"
        }
        else -> {
            "${this / GB}GB"
        }
    }
}

fun String.getBinName(): String {
    val index = this.lastIndexOf('/')
    return if (index in this.indices) {
        this.removeRange(0..index)
    } else {
        this
    }
}


fun File.childCount(): Int {
    return when {
        this.isDirectory -> this.listFiles(FileUtils.binFilter)?.size ?: 0
        else -> 0
    }
}